<template>
	<view class="wrap" style="height: 100vh">
		<js-error mode="bottom" ref="jsError"></js-error>
		<u-sticky class="u-sticky">
			<view class="cu-bar search" style="padding: 10px">
			  <u-search
			    v-model="barCode"
			    ref="uSearch"
			    :focus="focus"
			    placeholder="请先聚焦后扫描"
			    :show-action="false"
			    @search="confirm"
			  ></u-search>
			  <view style="margin-left: 10px; display: flex; flex-direction: column">
			    <u-icon @click="search" name="scan" size="50"></u-icon>
			  </view>
			</view>
		</u-sticky>
		<!-- -->
		<view v-if="flag">
			<!-- style="padding: 0 10px" -->
			<u-form :model="model" :rules="rules" ref="uForm" label-position="left" >
				<scroll-view
				  scroll-y="true"
				  :style="{ height: scrollViewHeight + 'px' }"
				  class="scroll-view-class"
				>
				<!-- class="bg-white  radius" -->
					<view class="bg-white  padding  margin-bottom shadow">
						<u-form-item label="工装编码"  label-width="220">
							{{ model.code || '' }}
						</u-form-item>
						<u-form-item label="工装尾号"  label-width="220">
							{{ model.lastNum || '' }}
						</u-form-item>
						<u-form-item label="工装名称" prop="gongxu_name" label-width="220">
							{{ model.name || '' }}
						</u-form-item>
						
						<u-form-item label="工装状态" prop="gongxu_name" label-width="220">
							{{ model.moldStatus || '' }}	
						</u-form-item>
						<u-form-item label="是否共模" prop="devName" label-width="220">
							{{ model.bcomomMode || '' }}	
						</u-form-item>
						<u-form-item label="存货名称" prop="devName" label-width="220">
							{{ model.basInv&&model.basInv.cinvname  || '' }}	
						</u-form-item>
						<u-form-item label="存货编码" prop="devName" label-width="220">
							{{ model.basInv&&model.basInv.cinvcode  || '' }}	
						</u-form-item>
						<u-form-item label="工序" prop="devName" label-width="220">
							{{ model.operCode  || '' }}	
						</u-form-item>
						<u-form-item label="购买日期" prop="buyDate" label-width="220">
							{{ model.buyDate  || '' }}	
						</u-form-item>
						<u-form-item label="使用日期" prop="useDate" label-width="220">
							{{ model.useDate  || '' }}	
						</u-form-item>
						<u-form-item label="设计寿命" prop="iquantity" label-width="220">
							{{ model.iquantity  || '' }}	
						</u-form-item>
						<u-form-item label="可用次数" prop="iqty" label-width="220">
							{{ model.iqty  || '' }}	
						</u-form-item>
						<u-form-item label="加工次数" prop="useQty" label-width="220">
							{{ model.useQty  || '' }}	
						</u-form-item>
						<u-form-item label="工装代码" prop="caddcode" label-width="220">
							{{ model.caddcode  || '' }}	
						</u-form-item>
						<u-form-item label="工装类型" prop="clsCode" label-width="220">
							{{ model.basMoldCls&&model.basMoldCls.name  || ''}}	
						</u-form-item>
						<u-form-item label="位置编码" prop="locationCode" label-width="220">
							{{ model.locationCode || '' }}	
						</u-form-item>
						<u-form-item label="位置名称" prop="locationName" label-width="220">
							{{ model.locationName || '' }}	
						</u-form-item>
						<u-form-item label="部门编码" prop="depCode" label-width="220">
							{{ model.depCode || ''}}	
						</u-form-item>
						<u-form-item label="部门名称" prop="depName" label-width="220">
							{{ model.depName || ''}}	
						</u-form-item>
						<u-form-item label="供应商名称" prop="venName" label-width="220">
							{{ model.venName || ''}}	
						</u-form-item>
						<u-form-item label="制作日期" prop="makeDate" label-width="220">
							{{ model.makeDate || ''}}	
						</u-form-item>
						<u-form-item label="安装日期" prop="installDate" label-width="220">
							{{ model.installDate || ''}}	
						</u-form-item>
						<u-form-item label="验收日期" prop="checkDate" label-width="220">
							{{ model.checkDate || ''}}	
						</u-form-item>
						<u-form-item label="保修截止日期" prop="expiryDate" label-width="220">
							{{ model.expiryDate || ''}}	
						</u-form-item>
						<u-form-item label="追加寿命" prop="addQty" label-width="220">
							{{ model.addQty || '' }}	
						</u-form-item>
						<u-form-item label="保养周期" prop="byQty" label-width="220">
							{{ model.byQty || '' }}	
						</u-form-item>
						<u-form-item label="点检人" prop="checker" label-width="220">
							{{ model.checker || '' }}	
						</u-form-item>
						<u-form-item label="备注信息" prop="remarks1" label-width="220" label-position="bottom">
							{{ model.remarks || '' }}	
						</u-form-item>
					</view>
								
				</scroll-view>
				
				
				
			</u-form>
			<!-- <view class="cu-bar" v-if="flagBtn"></view> -->
			<!-- v-if="flagBtn" -->
			<view class="form-footer cu-bar foot" v-if="flagBtn">
				<u-button class="btn" type="primary" @click="submitAdd">增加使用次数</u-button>
			</view>
			
		</view>
		<u-empty  style="height: 70vh;" text="请扫描工装"  v-if="!flag"></u-empty>
		
		<view>
			<movable-area class="movable-area1">
				<movable-view class="movable-view" :x="x" :y="y" direction="all">
					<view @click="handleSearch" class="custom-style" style="width: 90px; height: 70px; color: #fff; border-radius: 10rpx;">
						<view style="font-size: 16px;display: flex; flex-direction: column;text-align: center;">
							<text class="cuIcon-scan text-xxls text-blue"></text>
							<view class="text-blue">工装识别</view>
						</view>
					</view>
					
				</movable-view>
			</movable-area>
		</view>
	</view>
</template>

<script>
	import { hasPermission } from '@/common/fire.js'
	export default {
		data() {
			return {
				model: {},
				modelAdd: {},
				focus:false,
				barCode: "",
				rules: {
					lastNum:[
						{
							required: true,
							message: '请选择工装尾号',
							trigger: ['change','blur'],
						}
					]
				},
				barcode1:'',
				scrollViewHeight:0,
				formFooterHeight: 0,
				headerHeight: 0,
				x: 650, //x坐标
				y: 650, //y坐标
				flag:false,
				flagAdd:false,
				flagBtn: hasPermission('bas:mold:basMold:edit')
			}
		},
		// 计算每一个item的模具尾号
		onReady() {
			
			
		},
		mounted() {
			
			
		  this.calculateScrollViewHeight();
		},
		methods:{
			submitAdd(){
				// this.flagAdd = true
				// 并且页面锚点调转到class="targetAdd"
				uni.navigateTo({
					url: "/pages/asd/mold/addQtyModal?selIds=" + this.model.id,
				});


			},
			DateChange(item, e) {
			  console.log(item, e);
			  //   this.date = e.detail.value;
			  if (item === "stratDate") {
			    this.model.stratDate = e.detail.value;
			  } else if(item === "endDate"){
				this.model.endDate = e.detail.value;
			  }
			  this.$forceUpdate();
			},
			handleSearch(){
				if(this.vuex_config.deviceType === this.vuex_config.deviceTypeAPP){
					this.search()
				}else if(this.vuex_config.deviceType === this.vuex_config.deviceTypePDA){
					this.handleFocus()
				}
			},
			submit(){
				console.log(this.model.moldList)
				// 遍历 this.model.moldList
				let hasError = false;
				let hasErrorMsg = ''
				this.model.moldList.some((item,index) => {
				  if (!item.lastNum) {
				    hasErrorMsg = `工装编号"${item.basMold.code}"名称"${item.basMold.name}"请选择工装尾号`
				    hasError = true; // 设置错误标志
				    return true; // 中断 some 遍历
				  }
				  return false;
				});		
				if (hasError) {
				  this.$refs.jsError.showError('', hasErrorMsg , 'error');
				  return false;
				}
				this.model.barcode = this.barcode1
				const data = this.model
				this.$u.api.asd.saveBatch(data).then((res)=>{
					if(res.result == "true"){
						this.$u.toast(res.message)
						this.flag = false
						this.model = {}
					}else{
						this.$refs.jsError.showError('', res.message , 'error');
					}
				})
				
			},
			async calculateScrollViewHeight() {
			  	await this.$nextTick(); // 确保DOM更新完成
			  	const query = uni.createSelectorQuery().in(this);
				// 获取form-footer 的高度
				query.select(".form-footer").boundingClientRect((rect) => {
					if (rect && rect.height > 0) { // 确保rect有效且高度大于0
						this.formFooterHeight = rect.height;
					}
				});
				query.select(".u-sticky").boundingClientRect((rect) => {
					if (rect && rect.height > 0) { // 确保rect有效且高度大于0
					this.headerHeight = rect.height;
					// 获取屏幕高度
					const systemInfo = uni.getSystemInfoSync();
					const screenHeight = systemInfo.windowHeight;
					// 计算scroll-view高度
					this.scrollViewHeight = screenHeight - this.headerHeight - this.formFooterHeight -80;
					console.log(this.scrollViewHeight, 'this.scrollViewHeight');
					} else {
					console.error('无法获取.u-sticky的高度或高度为0');
					}
				}).exec();
			},
			handleFocus() {
			  var _that = this;
			  _that.focus = false;
			  setTimeout(() => {
			    _that.focus = true;
			  }, 500);
			},
			confirm() {
				this.focus = false
				console.log(this.barCode, 'barCode')
				this.barcode1 = this.barCode
				this.commonSearch(this.barCode)
			},
			search() {
				var _that = this;
				_that.focus = false				
				// const scanner = uni.requireNativePlugin('Ba-Scanner')
				// if(scanner === undefined){
				// 	uni.scanCode({
				// 		scanType: ["barCode", "qrCode"],
				// 		// onlyFromCamera: true,
				// 		success: async (res) => {
				// 			that.barCode = res.result;
				// 			await that.commonSearch(res.result)
				// 		},
				// 	});
				// }else{
				// 	scanner.onScan({
				// 			hintText: '',
				// 			isShowToast: false,
				// 			barcodeFormats: ["QR Code","Codabar"]
				// 		},
				// 		async (ret) => {
				// 			console.log('ret',ret)
				// 			if (ret.result) {
				// 				await that.commonSearch(ret.result)
				// 			}
				// 	});
				// }
				
				var mpaasScanModule = uni.requireNativePlugin("Mpaas-Scan-Module");
				mpaasScanModule.mpaasScan({
					// 扫码识别类型，参数可多选，qrCode、barCode，不设置，默认识别所有
					'scanType':  ['qrCode','barCode'],
					// 是否隐藏相册，默认false不隐藏
					'hideAlbum': false,
					//ios需要设置这个参数，只支持中英文 zh-Hans、en，默认中文                       
					'language' : 'en',
					//相册选择照片识别错误提示(ios)
					'failedMsg': '未识别到二维码，请重试',
					//Android支持全屏需要设置此参数
					'screenType': 'full'              
				},
				async (ret) => {
					console.log('ret',ret)
					if(ret.resp_message == 'success'){
						_that.barCode = ret.resp_result;
						await _that.commonSearch(ret.resp_result)
					}
				})
				
			},
			async commonSearch(barCode) {
				let that = this
				this.$u.api.asd.analysisMold({
					barCode,
				}).then(res => {
					if (res.result == 'true') {
						
						this.flag = true
						this.$u.api.asd.moldForm({id:res.data.id}).then(res => {
							this.model = res.basMold
						})
						
						this.$forceUpdate()
						console.log('model',res)
						setTimeout(()=>{
							that.makeSound("cg");
						},500)
						that.$u.toast('成功！');
					} else {
						setTimeout(()=>{
							that.makeSound("sb");
						},500)
						that.$refs.jsError.showError('', res.message, 'error');
					}
					
					setTimeout(() => {
						this.barCode = '';
					}, 500);
					if(this.vuex_config.deviceType === this.vuex_config.deviceTypePDA){
						this.handleFocus()
					}
							
				})
			
				setTimeout(() => {
					this.barCode = '';
				}, 500);
			
			},
			makeSound(name){
				console.log("=====testClick=====");
				let src = '/static/'+name+'.mp3';
				//实例化声音  
				const Audio = uni.createInnerAudioContext();
				Audio.autoplay = true;
				Audio.src = src; //音频地址  
				Audio.play(); //执行播放  
				Audio.onError((res) => {
				});
				Audio.onPause(function() {
					console.log('end');
					Audio.destroy();
				});
			},
			
		}
	}
</script>

<style  lang="scss">
	$all_width: 96rpx;
	$all_height: 96rpx;
	.movable-area1 {
	  z-index: 999;
	  height: 97vh;
	  width: 650rpx;
	  position: fixed;
	  right: $all_width;
	  top: -($all_height + 70rpx);
	  pointer-events: none; //此处要加，鼠标事件可以渗透
	
	  .movable-view {
	    width: $all_width;
	    height: $all_height;
	    pointer-events: auto; //恢复鼠标事件
	
	    image {
	      width: $all_width;
	      height: $all_height;
	    }
	  }
	}
	.cuIcon-titles{
		color:#0081ff;
		font-size: 50rpx;
	}
	.paddingForm{
		padding: 18rpx 28rpx;
	}
	.text-xxls{
		font-size: 60rpx;
	}
	.select-date-prompt{
		font-size: 28rpx;
		color: #dfdfdf !important;
	}
</style>